import {parseKey} from "../../../../babel-static/hooks";

export function toLetters(num) {
  "use strict";
  var mod = num % 26,
    pow = num / 26 | 0,
    out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
  return pow ? toLetters(pow) + out : out;
}

globalThis.__toLetters__ = toLetters

globalThis.rowAndColumnToKey = function (c, r) {
  return toLetters(c) + r
}

export function convertLetterToNumber(str) {
  var out = 0, len = str.length;
  for (let pos = 0; pos < len; pos++) {
    out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
  }
  return out;
}


export function resolveDefPOSV2(def) {
  def.srangeArr = def.range.split(':')
  if (def.srangeArr[0] === def.srangeArr[1]) {
    def.isSingle = true
    def.letterSingle = def.srangeArr[0]
  }
  def.rangePos = def.srangeArr.map(key => {
    let obj = parseKey(key)
    // console.log(obj)
    return obj
  })
  def.cArr = def.rangePos.map(v => v.c).sort(function (a, b) {
    return a - b;
  });
  def.rArr = def.rangePos.map(v => v.r).sort(function (a, b) {
    return a - b;
  });
  return def
}

export function Arr(len) {
  return new Array(len).fill()
}

export function parseKeyArr(key = '') {
  let row = key.match(/\d+/g)[0]
  let letter = key.replace(row, '')
  let columnIndex = convertLetterToNumber(letter)
  let rowIndex = parseInt(row)
  return [
    columnIndex,
    rowIndex,
    letter,
  ]
}

export function getSimpleCell(i, s_rowNum, s_columnNum) {
  let rowLineNum = Math.ceil((i + 1) / s_columnNum);
  let columnNum = i % s_columnNum + 1;
  let letter = toLetters(columnNum);
  let key = letter + rowLineNum;
  return {key, rowLineNum, columnNum, letter}
}

export function getCellInfo(i, s_rowNum, s_columnNum) {
  let {key, rowLineNum, columnNum, letter} = getSimpleCell(i, s_rowNum, s_columnNum)


  // let rowLineNum = Math.ceil((i + 1) / s_columnNum)
  // let columnNum = i % s_columnNum + 1
  let isEven = rowLineNum % 2 === 0;
  // let letter = toLetters(columnNum)
  let isLastRow = rowLineNum >= s_rowNum;
  let isLastColumn = columnNum >= s_columnNum;
  // let key = letter + rowLineNum
  return {
    isEven,
    letter,
    key,
    isLastRow,
    isLastColumn,
    rowLineNum,
    columnNum
  }
}

export function getRangeArrAllKeys(f, l) {
  // let fColumnIndex = convertLetterToNumber(f.slice(0, 1))
  // let fRowIndex = parseInt(f.slice(1))
  // let lColumnIndex = convertLetterToNumber(l.slice(0, 1))
  // let lRowIndex = parseInt(l.slice(1))

  let [fColumnIndex, fRowIndex] = parseKeyArr(f)
  let [lColumnIndex, lRowIndex] = parseKeyArr(f)
  // console.log(fColumnIndex, lColumnIndex)
  // let columnRange = ZY.lodash.range(fColumnIndex, lColumnIndex)
  // console.log(columnRange)
  let ret = []
  for (let ci = fColumnIndex; ci<lColumnIndex + 1; ci++) {
    // if (!ret[ci]) {
    //   ret[ci] = []
    // }
    for (let ri = fRowIndex; ri<lRowIndex + 1; ri++) {
      // if (!ret[ci][ri]) {
      //   ret[ci][ri] = []
      // }
      // let cindex = ci - 1
      // let rindex = ri - 1
      let letter = toLetters(ci)
      // console.log(ci, ri, letter)
      // let cellInfo = getCellInfo(cindex * rindex, rowNum, columnNum)
      ret.push(letter + ri)
    }
  }
  return ret;
}

function checkInRange(key, rangeArr) {
  // console.log(key, rangeArr)
  let f = rangeArr[0]
  let l = rangeArr[1]
  // let fColumnIndex = convertLetterToNumber(f.slice(0, 1))
  // let fRowIndex = parseInt(f.slice(1))
  // let lColumnIndex = convertLetterToNumber(l.slice(0, 1))
  // let lRowIndex = parseInt(l.slice(1))
  let [fColumnIndex, fRowIndex] = parseKeyArr(f)
  let [lColumnIndex, lRowIndex] = parseKeyArr(f)
  // console.log(fColumnIndex, lColumnIndex)
  // let columnRange = ZY.lodash.range(fColumnIndex, lColumnIndex)
  // console.log(columnRange)
  let ret = []
  for (let ci = fColumnIndex; ci<lColumnIndex + 1; ci++) {
    // if (!ret[ci]) {
    //   ret[ci] = []
    // }
    for (let ri = fRowIndex; ri<lRowIndex + 1; ri++) {
      // if (!ret[ci][ri]) {
      //   ret[ci][ri] = []
      // }
      // let cindex = ci - 1
      // let rindex = ri - 1
      let letter = toLetters(ci)
      // console.log(ci, ri, letter)
      // let cellInfo = getCellInfo(cindex * rindex, rowNum, columnNum)
      ret.push(letter + ri)
    }
  }
  return ret.includes(key)
  // console.log(key, ret)
}

export function getAllCells(defs = []) {
  let arr = [];
  let isInRange = {}
  defs.forEach(v => {
    if (v.rangeArr[0] === v.rangeArr[1]) {
      arr = arr.concat(v.rangeArr);
    } else {
      // console.log('sdsds', v.rangePos)


      let _a = []
      let [p1, p2] = v.rangePos;

      for (let c1 = p1.c; c1 <= p2.c; c1++) {
        for (let r1 = p1.r; r1 <= p2.r; r1++) {
          let key = toLetters(c1 + 1) + (r1 + 1);
          // console.log(key)
          _a.push(key);
          isInRange[key] = v.rangeArr[0]
        }
      }

      arr = arr.concat(_a);
    }
  })
  let a = [...new Set(arr)]
  // let isRangeKeys = Object.keys(isInRange)
  // console.log(a)
  return {
    cells: a
  };
}


export function getGridAreasStyleV2(defs = [], {
  startRowNum = 0,
  maxRowSize = 0,
  rowNum,
  columnNum
} = {}, print) {
  // let defsMap = defs.map(v => {
  //   v.rangeArr = v.range.split(':')
  //   return v
  // })
  // let cached = {}
  // console.log(maxRowSize)
  let defsMap  = defs;
  let finded = [];


  // console.time('getGridAreasStyleV2')
  // let arr = Arr(rowNum * columnNum).fill('.')
  let arr = Array.from({length: rowNum * columnNum}, function () { return '.' })
  let areas = ZY.lodash.chunk(arr, columnNum);

  let lodash = ZY.lodash;



  // areas.forEach((row, rowIndex) => {
  lodash.each(areas, function (row, rowIndex) {
    // lodash.each(row, function (col, colIndex) {
    // })

    for (let colIndex = 0; colIndex < row.length; colIndex++) {
      let rowIndexNum = Math.min(maxRowSize, rowIndex + startRowNum)
      // console.log(rowIndex + startRowNum)
      // let rowIndexNum =  rowIndex + startRowNum
      // let letter = toLetters(colIndex + 1) + (rowIndexNum + 1)
      // let cell = {
      //   c: colIndex,
      //   r: rowIndexNum
      // }

      // console.log(letter)

      lodash.forEach(defsMap, function (def) {
        if (def.isSingle) {
          // console.log(letter, cell, def.rangePosCell)
          if ( def.rangePosCell) {
            if ( def.rangePosCell.c === colIndex && def.rangePosCell.r === rowIndexNum) {
              areas[rowIndex][colIndex] = def.id
              finded.push(def.id)
            }
          }
          // if (letter === def.letterSingle) {
          //   areas[rowIndex][colIndex] = def.id
          //   finded.push(def.id)
          // }
        } else {
          if (Array.isArray(def.cArr) && Array.isArray(def.rArr)) {
            if (colIndex >= def.cArr[0]  && colIndex <= def.cArr[1]) {
              if (rowIndexNum >= def.rArr[0]  && rowIndexNum <= def.rArr[1]) {
                // console.log(def.cArr, def.rArr)
                areas[rowIndex][colIndex] = def.id
                finded.push(def.id)
              }
            }
          }
        }
      })
    }
  })

  let str = ''

  lodash.each(areas, function(area) {
    str = str + `"${area.join(' ')}"`
  })

  if (print) {
    console.log(areas, str)
  }

  // console.timeEnd('getGridAreasStyleV2')

  return {
    style: str,
    finded
  }
}


export function getGridAreasStyle(defs = [], {
  rowNum,
  columnNum
} = {}, print) {
  let defsMap = defs.map(v => {
    v.rangeArr = v.range.split(':')
    return v
  })
  // let cached = {}

  let arr =Arr(rowNum * columnNum).fill('.')
  let areas = ZY.lodash.chunk(arr, columnNum)

  areas.forEach((row, rowIndex) => {
    row.forEach((col, colIndex) => {
      let letter = toLetters(colIndex + 1) + (rowIndex + 1)
      let cell = {
        c: colIndex,
        r: rowIndex
      }

      defsMap.forEach(def => {
        if (def.isSingle) {
          // console.log(letter, def.letterSingle)
          if (letter === def.letterSingle) {
            areas[rowIndex][colIndex] = def.id
          }
        } else {
          if (Array.isArray(def.cArr) && Array.isArray(def.rArr)) {
            if (cell.c >= def.cArr[0]  && cell.c <= def.cArr[1]) {
              if (cell.r >= def.rArr[0]  && cell.r <= def.rArr[1]) {
                // console.log(def.cArr, def.rArr)
                areas[rowIndex][colIndex] = def.id
              }
            }
          }
        }
      })

    })
  })

  let str = ''

  areas.forEach(area => {
    str = str + `"${area.join(' ')}"`
  })

  if (print) {
    console.log(areas, str)
  }

  return str
}
